package com.ikas.ai.server.module.system.controller;

import com.github.pagehelper.PageInfo;
import com.ikas.ai.handle.JsonResult;
import com.ikas.ai.handle.JsonResultType;
import com.ikas.ai.server.aop.ColumnCheck;
import com.ikas.ai.server.error.BusinessException;
import com.ikas.ai.server.module.AbstractBean;
import com.ikas.ai.server.module.system.model.LogOpsType;
import com.ikas.ai.server.module.system.model.Permission;
import com.ikas.ai.server.module.system.model.Role;
import com.ikas.ai.server.module.system.model.vo.RoleAuthVo;
import com.ikas.ai.server.module.system.service.PermissionService;
import com.ikas.ai.server.module.system.service.RoleService;
import com.ikas.ai.server.module.system.service.UserService;
import com.ikas.ai.utils.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;

/**
 * 系统管理-角色管理
 *
 * @author hxh
 * @description 角色管理操作管理类
 */
@SuppressWarnings("all")
@Validated
@RestController
@RequestMapping("/system/role")
public class RoleController extends AbstractBean {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;


    private static final String COLUMN_NAMES = "id,name,createTime";

    /**
     * 角色分页列表查询
     *
     * @param name   角色名称
     * @param remark 备注信息
     * @param page   页码
     * @param size   每页显示条数
     * @param sc     排序字段
     * @param s0     排序
     * @return {@link JsonResult}
     * @description 角色列表分页查询
     * @date 2021/12/1
     */
    @GetMapping("/list")
    public String pageQueryRoleList(HttpServletRequest request,
                                    @RequestParam(value = "name", required = false) String name,
                                    @RequestParam(value = "remark", required = false) String remark,
                                    @RequestParam(value = "page", required = false) Integer pageNo,
                                    @RequestParam(value = "size", required = false) Integer pageSize,
                                    @RequestParam(value = "sc", required = false) @ColumnCheck(value = COLUMN_NAMES) String sortColumnName,
                                    @RequestParam(value = "so", required = false) String sortOrder) {
        JsonResult result = new JsonResult(JsonResultType.OK);
        PageUtil.configPageHelper(pageNo, pageSize, sortColumnName, sortOrder, "id", "asc");
        List<Role> roles = roleService.getRoles(name, remark);
        PageInfo<Role> pageInfo = new PageInfo<>(roles);
        result.add(pageInfo);
        return result.toJSON();
    }

    /**
     * 角色信息新增修改
     * 需要参数校验时，@Valid和BindingResult参数一定要，否则在实体上的参数校验将会无效
     *
     * @param request
     * @param role
     * @param bindingResult
     * @return
     */
    @PostMapping("/update")
    public String updateRole(HttpServletRequest request, @Valid @RequestBody Role role, BindingResult bindingResult) {
        JsonResult result = new JsonResult(JsonResultType.OK);
        if (role.getId() != null && role.getId() > 0) {
            roleService.updateRole(role);
            this.logOperation(request, LogOpsType.ROLE_MANAGE, String.format("修改用户角色-%s", role.getName()));
        } else {
            roleService.addRole(role, getUser());
            this.logOperation(request, LogOpsType.ROLE_MANAGE, String.format("增加用户角色-%s[%d]", role.getName(), role.getId()));
        }
        return result.toJSON();
    }

    /**
     * 删除用户角色
     *
     * @param request
     * @param ids
     * @return
     */
    @PostMapping("/{ids}")
    public String deleteRole(HttpServletRequest request, @PathVariable(name = "ids") String ids) {
        this.logOperation(request, LogOpsType.ROLE_MANAGE, String.format("删除用户角色，角色ID为[%s]", ids));
        JsonResult result = new JsonResult(JsonResultType.OK);
        String[] ss = ids.split(",");
        if (ss.length == 1) {
            roleService.deleteRole(Long.valueOf(ss[0]));
        } else if (ss.length > 1) {
            List<Long> arr = new ArrayList<>();
            for (String s : ss) {
                Long id = Long.valueOf(s);
                if (id == 1) {
                    continue;  // 系统角色禁止删除
                }
                arr.add(id);
            }
            roleService.deleteRoles(arr);
        } else {
            throw new RuntimeException("请选择要删除的角色");
        }
        return result.toJSON();
    }

    /**
     * 获取授权菜单
     *
     * @return
     */
    @GetMapping("/menuList")
    public String menuList() {
        JsonResult jsonResult = new JsonResult(JsonResultType.OK);
        List<Permission> list = permissionService.pageQueryPermissionList(null, null, null);
        jsonResult.add(list);
        return jsonResult.toJSON();
    }

    /**
     * 根据角色id获取对应的菜单列表
     *
     * @param roleId
     * @return
     */
    @GetMapping("/roleAuthList/{roleId}")
    public String roleAuthList(@PathVariable("roleId") @Valid @NotNull(message = "角色id必填") Long roleId) {
        JsonResult jsonResult = new JsonResult(JsonResultType.OK);
        List<Permission> list = permissionService.getPermissionListByRoleId(roleId);
        jsonResult.add("menuIdList", list);
        return jsonResult.toJSON();
    }

    /**
     * 角色授权操作
     *
     * @return
     */
    @PostMapping("/setAuth")
    @Transactional(rollbackFor = BusinessException.class)
    public String setAuth(HttpServletRequest request, @RequestBody @Valid RoleAuthVo roleAuthVo, BindingResult bindingResult) {
        JsonResult jsonResult = new JsonResult(JsonResultType.OK);
        Assert.notEmpty(roleAuthVo.getMenuIdList(), "请选择菜单权限");
        permissionService.setAuth(roleAuthVo);
        //清除shiro授权缓存
        roleService.reloadAuthorizing(roleAuthVo.getRoleId());
        this.logOperation(request, LogOpsType.ROLE_MANAGE, String.format("角色(ID=%s)授权操作", roleAuthVo.getRoleId()));
        return jsonResult.toJSON();
    }


}
